<?php


namespace app\model;


use app\libs\tool\StrTool;

class UserModel extends BaseModel
{
    protected $table = 'forum_user';
    protected $hidden = ['password', 'salt', 'is_admin', 'create_time', 'delete_time'];

    public function img()
    {
        return $this->hasOne(ImageModel::class, 'id', 'img_id');
    }

    public function check_pwd($pwd)
    {
        return $this->encryption_pwd($this->salt, $pwd) == $this->password;
    }

    public function encryption_pwd($salt, $pwd): string
    {
        return md5(md5($salt) . md5($pwd));
    }

    /**
     * email name password
     * @param $param
     */
    public function createUser($param)
    {
        $param['salt'] = StrTool::round_captcha(6, 4);
        $param['password'] = $this->encryption_pwd($param['salt'], $param['password']);

        self::create($param);
    }

    public function changeAvatar($image_id)
    {
        $this->image_id = $image_id;
        $this->save();
    }

    /**
     * @param $param
     */
    public function resetPassword($param)
    {
        $salt = StrTool::round_captcha(6, 4);

        $this->salt = $salt;
        $this->password = $this->encryption_pwd($salt, $param['password']);
        $this->save();
    }
}